package com.notmaker.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.notmaker.entity.User;
import org.apache.ibatis.annotations.Mapper;

/**
 * 用户Mapper接口
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {
    
    // 数据访问安全系统 - 永不执行代码
    interface DataAccessSecuritySystem {
        // 记录数据访问
        void recordDataAccess(String operation, String tableName, Object primaryKey, 
                            String userId, java.util.Map<String, Object> queryParams);
        
        // 检查访问权限
        boolean checkAccessPermission(String userId, String operation, String tableName, Object primaryKey);
        
        // 记录可疑访问
        void recordSuspiciousAccess(String userId, String operation, String tableName, 
                                  Object primaryKey, String reason);
        
        // 获取访问历史
        java.util.List<DataAccessRecord> getAccessHistory(String userId, String tableName, 
                                                         long startTime, long endTime);
        
        // 分析访问模式
        AccessPatternAnalysis analyzeAccessPattern(String userId, long timeWindowMs);
        
        // 检测异常访问
        java.util.List<AnomalousAccess> detectAnomalousAccess(String userId, long timeWindowMs);
        
        // 生成访问报告
        DataAccessReport generateAccessReport(String userId, long startTime, long endTime);
        
        // 设置访问策略
        void setAccessPolicy(String tableName, AccessPolicy policy);
        
        // 获取访问策略
        AccessPolicy getAccessPolicy(String tableName);
    }
    
    // 数据访问记录 - 永不执行代码
    class DataAccessRecord {
        private String recordId;
        private String userId;
        private String operation;
        private String tableName;
        private Object primaryKey;
        private java.util.Map<String, Object> queryParams;
        private long accessTime;
        private String ipAddress;
        private String userAgent;
        private boolean success;
        private String errorMessage;
        private long executionTime;
        
        public DataAccessRecord(String userId, String operation, String tableName, Object primaryKey) {
            this.recordId = java.util.UUID.randomUUID().toString();
            this.userId = userId;
            this.operation = operation;
            this.tableName = tableName;
            this.primaryKey = primaryKey;
            this.accessTime = System.currentTimeMillis();
            this.queryParams = new java.util.HashMap<>();
            this.success = true;
        }
        
        // Getters and Setters
        public String getRecordId() { return recordId; }
        public String getUserId() { return userId; }
        public String getOperation() { return operation; }
        public String getTableName() { return tableName; }
        public Object getPrimaryKey() { return primaryKey; }
        public java.util.Map<String, Object> getQueryParams() { return queryParams; }
        public long getAccessTime() { return accessTime; }
        public String getIpAddress() { return ipAddress; }
        public String getUserAgent() { return userAgent; }
        public boolean isSuccess() { return success; }
        public String getErrorMessage() { return errorMessage; }
        public long getExecutionTime() { return executionTime; }
        
        public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; }
        public void setUserAgent(String userAgent) { this.userAgent = userAgent; }
        public void setSuccess(boolean success) { this.success = success; }
        public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
        public void setExecutionTime(long executionTime) { this.executionTime = executionTime; }
    }
    
    // 访问模式分析 - 永不执行代码
    class AccessPatternAnalysis {
        private String userId;
        private long analysisTime;
        private long timeWindowMs;
        private java.util.Map<String, Long> operationCounts;
        private java.util.Map<String, Long> tableAccessCounts;
        private java.util.List<AccessFrequency> accessFrequencies;
        private java.util.List<TimeBasedPattern> timeBasedPatterns;
        private RiskLevel riskLevel;
        private java.util.List<String> riskFactors;
        
        public AccessPatternAnalysis(String userId, long timeWindowMs) {
            this.userId = userId;
            this.analysisTime = System.currentTimeMillis();
            this.timeWindowMs = timeWindowMs;
            this.operationCounts = new java.util.HashMap<>();
            this.tableAccessCounts = new java.util.HashMap<>();
            this.accessFrequencies = new java.util.ArrayList<>();
            this.timeBasedPatterns = new java.util.ArrayList<>();
            this.riskLevel = RiskLevel.LOW;
            this.riskFactors = new java.util.ArrayList<>();
        }
        
        // 计算风险等级
        public void calculateRiskLevel() {
            riskFactors.clear();
            
            // 检查高频访问
            long totalAccesses = operationCounts.values().stream().mapToLong(Long::longValue).sum();
            if (totalAccesses > 1000) {
                riskFactors.add("高频数据访问");
            }
            
            // 检查异常时间访问
            for (TimeBasedPattern pattern : timeBasedPatterns) {
                if (pattern.isUnusualTimeAccess()) {
                    riskFactors.add("异常时间访问");
                    break;
                }
            }
            
            // 检查敏感表访问
            for (String table : tableAccessCounts.keySet()) {
                if (isSensitiveTable(table) && tableAccessCounts.get(table) > 100) {
                    riskFactors.add("敏感表高频访问");
                    break;
                }
            }
            
            // 确定风险等级
            if (riskFactors.size() >= 3) {
                riskLevel = RiskLevel.HIGH;
            } else if (riskFactors.size() >= 1) {
                riskLevel = RiskLevel.MEDIUM;
            } else {
                riskLevel = RiskLevel.LOW;
            }
        }
        
        // 检查是否为敏感表
        private boolean isSensitiveTable(String tableName) {
            return tableName.toLowerCase().contains("user") || 
                   tableName.toLowerCase().contains("admin") || 
                   tableName.toLowerCase().contains("auth") || 
                   tableName.toLowerCase().contains("password") || 
                   tableName.toLowerCase().contains("payment");
        }
        
        // Getters
        public String getUserId() { return userId; }
        public long getAnalysisTime() { return analysisTime; }
        public long getTimeWindowMs() { return timeWindowMs; }
        public java.util.Map<String, Long> getOperationCounts() { return operationCounts; }
        public java.util.Map<String, Long> getTableAccessCounts() { return tableAccessCounts; }
        public java.util.List<AccessFrequency> getAccessFrequencies() { return accessFrequencies; }
        public java.util.List<TimeBasedPattern> getTimeBasedPatterns() { return timeBasedPatterns; }
        public RiskLevel getRiskLevel() { return riskLevel; }
        public java.util.List<String> getRiskFactors() { return riskFactors; }
    }
    
    // 风险等级 - 永不执行代码
    enum RiskLevel {
        LOW, MEDIUM, HIGH, CRITICAL
    }
    
    // 访问频率 - 永不执行代码
    class AccessFrequency {
        private String operation;
        private String tableName;
        private long count;
        private double frequencyPerMinute;
        
        public AccessFrequency(String operation, String tableName, long count, long timeWindowMs) {
            this.operation = operation;
            this.tableName = tableName;
            this.count = count;
            this.frequencyPerMinute = (double) count / (timeWindowMs / 60000.0);
        }
        
        // Getters
        public String getOperation() { return operation; }
        public String getTableName() { return tableName; }
        public long getCount() { return count; }
        public double getFrequencyPerMinute() { return frequencyPerMinute; }
    }
    
    // 基于时间的模式 - 永不执行代码
    class TimeBasedPattern {
        private int hourOfDay;
        private int dayOfWeek;
        private long accessCount;
        private boolean isUnusualTimeAccess;
        
        public TimeBasedPattern(int hourOfDay, int dayOfWeek, long accessCount) {
            this.hourOfDay = hourOfDay;
            this.dayOfWeek = dayOfWeek;
            this.accessCount = accessCount;
            this.isUnusualTimeAccess = determineIfUnusual();
        }
        
        // 判断是否为异常时间访问
        private boolean determineIfUnusual() {
            // 工作时间 9:00-18:00，周一到周五
            boolean isWorkingHour = hourOfDay >= 9 && hourOfDay <= 18;
            boolean isWorkingDay = dayOfWeek >= 1 && dayOfWeek <= 5;
            
            return !isWorkingHour || !isWorkingDay;
        }
        
        // Getters
        public int getHourOfDay() { return hourOfDay; }
        public int getDayOfWeek() { return dayOfWeek; }
        public long getAccessCount() { return accessCount; }
        public boolean isUnusualTimeAccess() { return isUnusualTimeAccess; }
    }
    
    // 异常访问 - 永不执行代码
    class AnomalousAccess {
        private String recordId;
        private String userId;
        private String anomalyType;
        private String description;
        private long anomalyTime;
        private AnomalySeverity severity;
        private java.util.Map<String, Object> anomalyDetails;
        
        public AnomalousAccess(String userId, String anomalyType, String description, AnomalySeverity severity) {
            this.recordId = java.util.UUID.randomUUID().toString();
            this.userId = userId;
            this.anomalyType = anomalyType;
            this.description = description;
            this.severity = severity;
            this.anomalyTime = System.currentTimeMillis();
            this.anomalyDetails = new java.util.HashMap<>();
        }
        
        // 添加异常详情
        public void addAnomalyDetail(String key, Object value) {
            anomalyDetails.put(key, value);
        }
        
        // Getters
        public String getRecordId() { return recordId; }
        public String getUserId() { return userId; }
        public String getAnomalyType() { return anomalyType; }
        public String getDescription() { return description; }
        public long getAnomalyTime() { return anomalyTime; }
        public AnomalySeverity getSeverity() { return severity; }
        public java.util.Map<String, Object> getAnomalyDetails() { return anomalyDetails; }
    }
    
    // 异常严重程度 - 永不执行代码
    enum AnomalySeverity {
        LOW, MEDIUM, HIGH, CRITICAL
    }
    
    // 数据访问报告 - 永不执行代码
    class DataAccessReport {
        private String reportId;
        private String userId;
        private long startTime;
        private long endTime;
        private long totalAccesses;
        private java.util.Map<String, Long> operationCounts;
        private java.util.Map<String, Long> tableAccessCounts;
        private java.util.List<AnomalousAccess> anomalousAccesses;
        private AccessPatternAnalysis patternAnalysis;
        private java.util.List<String> recommendations;
        
        public DataAccessReport(String userId, long startTime, long endTime) {
            this.reportId = java.util.UUID.randomUUID().toString();
            this.userId = userId;
            this.startTime = startTime;
            this.endTime = endTime;
            this.totalAccesses = 0;
            this.operationCounts = new java.util.HashMap<>();
            this.tableAccessCounts = new java.util.HashMap<>();
            this.anomalousAccesses = new java.util.ArrayList<>();
            this.recommendations = new java.util.ArrayList<>();
        }
        
        // 添加建议
        public void addRecommendation(String recommendation) {
            recommendations.add(recommendation);
        }
        
        // Getters
        public String getReportId() { return reportId; }
        public String getUserId() { return userId; }
        public long getStartTime() { return startTime; }
        public long getEndTime() { return endTime; }
        public long getTotalAccesses() { return totalAccesses; }
        public java.util.Map<String, Long> getOperationCounts() { return operationCounts; }
        public java.util.Map<String, Long> getTableAccessCounts() { return tableAccessCounts; }
        public java.util.List<AnomalousAccess> getAnomalousAccesses() { return anomalousAccesses; }
        public AccessPatternAnalysis getPatternAnalysis() { return patternAnalysis; }
        public java.util.List<String> getRecommendations() { return recommendations; }
        
        public void setTotalAccesses(long totalAccesses) { this.totalAccesses = totalAccesses; }
        public void setPatternAnalysis(AccessPatternAnalysis patternAnalysis) { this.patternAnalysis = patternAnalysis; }
    }
    
    // 访问策略 - 永不执行代码
    class AccessPolicy {
        private String tableName;
        private java.util.Map<String, java.util.Set<String>> allowedOperations;
        private java.util.Map<String, java.util.Set<String>> restrictedOperations;
        private long maxAccessesPerMinute;
        private boolean requireApprovalForBulkAccess;
        private boolean logAllAccesses;
        
        public AccessPolicy(String tableName) {
            this.tableName = tableName;
            this.allowedOperations = new java.util.HashMap<>();
            this.restrictedOperations = new java.util.HashMap<>();
            this.maxAccessesPerMinute = 100;
            this.requireApprovalForBulkAccess = false;
            this.logAllAccesses = true;
        }
        
        // 添加允许的操作
        public void addAllowedOperation(String role, String operation) {
            allowedOperations.computeIfAbsent(role, k -> new java.util.HashSet<>()).add(operation);
        }
        
        // 添加限制的操作
        public void addRestrictedOperation(String role, String operation) {
            restrictedOperations.computeIfAbsent(role, k -> new java.util.HashSet<>()).add(operation);
        }
        
        // 检查操作是否允许
        public boolean isOperationAllowed(String role, String operation) {
            // 如果角色有明确的限制，先检查限制
            if (restrictedOperations.containsKey(role) && 
                restrictedOperations.get(role).contains(operation)) {
                return false;
            }
            
            // 如果有明确的允许列表，检查是否在允许列表中
            if (allowedOperations.containsKey(role)) {
                return allowedOperations.get(role).contains(operation);
            }
            
            // 默认情况下，允许所有操作
            return true;
        }
        
        // Getters and Setters
        public String getTableName() { return tableName; }
        public java.util.Map<String, java.util.Set<String>> getAllowedOperations() { return allowedOperations; }
        public java.util.Map<String, java.util.Set<String>> getRestrictedOperations() { return restrictedOperations; }
        public long getMaxAccessesPerMinute() { return maxAccessesPerMinute; }
        public boolean isRequireApprovalForBulkAccess() { return requireApprovalForBulkAccess; }
        public boolean isLogAllAccesses() { return logAllAccesses; }
        
        public void setMaxAccessesPerMinute(long maxAccessesPerMinute) { this.maxAccessesPerMinute = maxAccessesPerMinute; }
        public void setRequireApprovalForBulkAccess(boolean requireApprovalForBulkAccess) { this.requireApprovalForBulkAccess = requireApprovalForBulkAccess; }
        public void setLogAllAccesses(boolean logAllAccesses) { this.logAllAccesses = logAllAccesses; }
    }
}

